package com.gree.gateway.filter;


import com.gree.gateway.config.properties.PermitProperties;
import com.gree.gateway.config.properties.SecurityProperties;
import com.gree.gateway.utils.IpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Import;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.function.Consumer;

/**
 * Created by 180551 on 2019/6/12.
 * 全局过滤器
 */
@Component
@Import(SecurityProperties.class)
public class AuthorizeFilter implements GlobalFilter, Ordered {

    @Autowired
    SecurityProperties securityProperties;

    private  final Logger logger = LoggerFactory.getLogger(AuthorizeFilter.class);

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request =exchange.getRequest();

        String ip = IpUtils.getRealIpAddress(request);
        Consumer<HttpHeaders> httpHeaders = httpHeader -> {
            httpHeader.add("realip", ip);
        };
        request = exchange.getRequest().mutate()
                .headers(httpHeaders)
                .build();

        String url = request.getPath().value();
        if(IsIgnoreUrl(url)){
            ServerHttpRequest host = exchange.getRequest().mutate().header("absoluteurl", url).build();
            ServerWebExchange build = exchange.mutate().request(host).build();
            return chain.filter(build);
        }
        return chain.filter(exchange.mutate().request(request).build());
    }

    @Override
    public int getOrder() {
        return 0;
    }


    private boolean IsIgnoreUrl(String path) {
        PathMatcher matcher = new AntPathMatcher();
        PermitProperties ignore = securityProperties.getIgnore();
        for (String ignoreUrlPattern : ignore.getUrls()){
            if(matcher.match(ignoreUrlPattern,path)){
                return true;
            }
        }
        return false;
    }
}
